var utils = require("../utils.js");
var treasure_chest = {
  go_page_from_home() {
    sleep(5 * 1000);
    if (utils.exists_text("百度") && utils.exists_text("福利")) {
      utils.click_text("福利");
      sleep(2 * 1000);
      this.init();
    } else {
      this.end();
    }
  },
  init() {
    var ad_ui_text = utils.click_text_starts_with("看广告再得");
    if (ad_ui_text) {
      this.execute(ad_ui_text.text());
      return;
    }
    var video_ui_text = utils.click_text_starts_with("观看视频再得");
    if (video_ui_text) {
      this.execute(video_ui_text.text());
      return;
    }
    sleep(2 * 1000);
    utils.click_text_starts_with("立即收下");
    sleep(2 * 1000);
    utils.click_text_starts_with("开心收下");

    if (utils.click_text("开宝箱得金币")) {
      sleep(2 * 1000);
      var video_ui_text_chest = utils.click_text_starts_with("观看视频再得");
      if (video_ui_text_chest) {
        this.execute(video_ui_text_chest.text());
        return;
      }
    }
  },
  execute(content) {
    console.log("treasure_chest execute:", content);
    var matchGold = content.match(/(\d+)/g);
    var gold = parseInt(Array.isArray(matchGold) ? matchGold[0] : 0);
    console.log("treasure_chest execute:", gold);
    sleep(2 * 1000);
    console.log("treasure_chest execute:", "2s");
    sleep(random(32, 35) * 1000);
    console.log("treasure_chest execute:", "35s");
    sleep(5 * 1000);
    if (utils.click_text_starts_with("查看详情")) {
      console.log("treasure_chest execute:", "找到查看详情");
      toast("找到查看详情");
      utils.swipeUp(8, 100);
      back();
      sleep(5 * 1000);
      back();
    } else {
      console.log("treasure_chest execute:", "没找到查看详情");
      toast("没找到查看详情");
      back();
    }
    sleep(2 * 1000);
    this.after();
  },

  after() {
    console.log("treasure_chest after:");
    var uiText = utils.click_text_starts_with("再看一个领取");
    if (uiText) {
      this.execute(uiText.text());
    } else if (utils.exists_text("返回继续完成任务")) {
      utils.click_text("换个视频");
      this.execute("换个视频");
    } else {
      this.end();
    }
  },
  end() {
    sleep(2 * 1000);
    if (!utils.click_text_starts_with("立即收下")) {
      utils.click_text_starts_with("开心收下");
    }
    sleep(2 * 1000);

    if (utils.exists_text_starts_with("看广告再得")) {
      this.init();
      return;
    }
    if (!utils.click_text("百度")) {
      console.log("treasure_chest end:", "没找到【百度】");
    }
    console.log("treasure_chest end:");
    this.next();
  },
  next() {
    console.log("treasure_chest next:");
  },
};
module.exports = treasure_chest;
